package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Verification;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IVerificationService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IVerificationService codeService;

    //登录操作
    @PostMapping
    @ResponseBody
    public Object login(String email,String password){
        JSONResult json =new JSONResult();
        try{
        //查询是否存在这个用户
        User user = userService.login(email, password);
        //如果为空,则报出异常
        //如果查询到,就把当前这个而用户设置进去
            UserContext.setCurrentUser(user);
            json.setData(user);
        }catch (Exception e){
            json.mark(e.getMessage());
        }

        return json;
    }

    //注销操作
    @DeleteMapping
    @ResponseBody
    public Object logout(HttpSession session){
        JSONResult json =new JSONResult();
        //销毁在session中的所有数据
        session.invalidate();
        return json;
    }

    //验证邮箱操作
    @PostMapping("/email")
    @ResponseBody
    public Object getEmail(String email){
        JSONResult result =new JSONResult();
        try{
            User user = userService.login(email, null);

            int num = (int) (Math.random() * 8999) + 1000 + 1;
            //HtmlEmail email=new HtmlEmail();//创建一个HtmlEmail实例对象
            //email.setHostName("smtp.163.com");//邮箱的SMTP服务器，一般123邮箱的是smtp.123.com,qq邮箱为smtp.qq.com
            //email.setCharset("utf-8");//设置发送的字符类型
            //email.addTo("xxxxxxxxxxx@qq.com");//设置收件人
            //email.setFrom("xxxxxxxxxx@163.com","aa");//发送人的邮箱为自己的，用户名可以随便填
            //email.setAuthentication("xxxxxxxxxx@163.com","xxxxxxxx");//设置发送人到的邮箱和用户名和授权码(授权码是自己设置的)

            Verification code = new Verification();
            code.setUserId(user.getId());
            code.setCode(num);

            codeService.saveOrUpdate(code);

        }catch (Exception e){
            e.printStackTrace();
            result.mark("用户名错误");
        }
        return result;
    }

    //查询验证码
    @GetMapping("/code")
    @ResponseBody
    public Object getCode(Long userId){
        return codeService.selectCodeByUserId(userId);
    }

    //查询验证码
    @PostMapping("/checkCode")
    @ResponseBody
    public Object checkCode(int code,String password){
        JSONResult result = new JSONResult();
        try{
            codeService.checkCode(code,password);
        }catch(Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
